package com.ruyuan.payment.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.ruyuan.payment.server.context.LoginMemberContext;
import com.ruyuan.payment.server.resp.MemberLoginResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器：Spring框架特有的，常用于登录校验，权限校验，请求日志打印
 */
@Component
public class LoginMemberInterceptor implements HandlerInterceptor {

    private static final Logger LOG = LoggerFactory.getLogger(LoginMemberInterceptor.class);

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取header的token参数
        String token = request.getHeader("token");
        LOG.info("获取登录token：{}", token);
        Object object = redisTemplate.opsForValue().get(token);
        LOG.info("获取登录用户：{}", object);
        LoginMemberContext.setMember(JSON.parseObject((String) object, MemberLoginResp.class));
        return true;
    }

}
